<template>
  <div>
    <!-- 搜索--------------------------------- -->
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>{{$t('common.filterSearch')}}</span>
        <el-button
          style="float: right"
          @click="fetchData()"
          type="primary"
          size="small"
        >
          {{ $t('common.search') }}
        </el-button>
      </div>
      <div style="margin-top: 25px">
        <el-form :inline="true" size="small" label-width="140px">
          <el-form-item :label="$t('examlist.search.id')">
            <el-input
              style="width: 203px"
              v-model="searchObj.examId"
              :placeholder="$t('examlist.search.plid')"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('examlist.search.name')">
            <el-input
              style="width: 230px margin-left"
              v-model="searchObj.title"
              :placeholder="$t('examlist.search.plname')"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('examlist.search.type')">
            <el-input
              style="width: 203px margin-left"
              v-model="searchObj.type"
              :placeholder="$t('examlist.search.pltype')"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- --------------------------------- -->
       <!--导入按钮 -->
    <el-button type="primary" @click="importData">
      <i class="fa fa-plus" />{{ $t('common.import') }}
    </el-button>
    <!-- 导出按钮 -->
     <!-- 导出按钮 -->

     <el-button type="primary" @click="exportData" style="margin-left:10px"
            > {{ $t('common.export') }}</el-button
          >
    <!-- 添加-------------------------------- -->
    <div align="right">

      <el-button type="success" @click="addExam" icon="el-icon-plus"
        >{{$t('common.add')}}</el-button
      >
    </div>
     <!-- 批量删除 -->
    <div>
      <el-button type="danger" size="mini" @click="removeRows()">{{ $t('common.bulkDelete') }}</el-button>
    </div>
    <!-- --------------------------------------列表页 -->
    <el-table :data="list" border fit highlight-current-row @selection-change="handleSelectionChange">
       <el-table-column type="selection" width="55" />
      <el-table-column :label="$t('examlist.table.examId')" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.examId }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('examlist.table.title')" align="center">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('examlist.table.type')" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('examlist.table.image')" align="center">
        <template slot-scope="{ row, $index }">
          <img :src="row.image" alt="" style="width: 130px; height: 100px" />
        </template>
      </el-table-column>

      <el-table-column :label="$t('examlist.table.viewNum')" align="center">
        <template slot-scope="scope">
          <el-tag size="warning">{{ scope.row.viewNum }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column :label="$t('examlist.table.startTime')" align="center">
        <template slot-scope="scope">
          <span style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;display:block"  >
          {{ dateFormat(scope.row.startTime) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('examlist.table.endTime')" align="center">
        <template slot-scope="scope">
          <span style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;display:block"  >
          {{ dateFormat(scope.row.endTime) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('common.operate')"
        align="center"
        width="330"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            type="info"
            size="mini"
            icon="el-icon-view"
            @click="searchExam(row.examId)"
            >{{ $t('common.see') }}
          </el-button
          >
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editExam(row)"
          >
            {{ $t('common.update') }}
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="delExam(row.examId)"
          >
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- --------------------------------------- -->
    <!-- ----------------------------------分页 -->
    <div class="block" style="float: right; margin-top: 20px">
      <!-- <span class="demonstration">显示总数</span> -->
      <el-pagination
        background
        @current-change="fetchData"
        :current-page.sync="page_num"
        :page-size="page_size"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- ---------------------------------------对话框-->
    <el-dialog
      :title="Exam.examId ? '修改考试信息' : '添加考试信息'"
      :visible.sync="dialogFormVisible"
    >
      <el-form style="width: 80%" :model="Exam" :rules="rules" ref="ruleForm">
        <el-form-item label="知识专题：" label-width="100px" prop="title">
          <!-- <el-input autocomplete="off" v-model="Exam.title"></el-input> -->
          <el-select v-model="Exam.title" placeholder="请选择文章类型">
          <el-option label="养生知识专题" value="养生知识专题"></el-option>
          <el-option label="水上知识专题" value="水上知识专题"></el-option>
          <el-option label="职业健康专题" value="职业健康专题"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
        <el-button
          type="success"
          @click="addType"
          icon="el-icon-plus"
        ></el-button>
        </el-form-item>
        <el-form-item label="类型：" label-width="100px" prop="type">
          <el-input autocomplete="off" v-model="Exam.type"></el-input>
        </el-form-item>

        <el-form-item label="观看人数：" label-width="100px" prop="viewNum">
          <el-input autocomplete="off" v-model.number="Exam.viewNum"></el-input>
        </el-form-item>

        <!-- 上传图片 -->
        <el-form-item label="考试图片：" label-width="100px">
          <el-upload
            class="avatar-uploader"
            action="http://42.194.159.131:8080/pic/imgUpload?path=knowledge"
            :headers="headers"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="Exam.image" :src="Exam.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label-width="100px" label="开题时间：" prop="startTime">
          <el-date-picker
            v-model="Exam.startTime"
            type="datetime"
            placeholder="选择日期时间"

          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label-width="100px" label="截至时间：" prop="endTime">
          <el-date-picker
            v-model="Exam.endTime"
            type="datetime"
            placeholder="选择日期时间"

          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addorupdateExam">确 定</el-button>
      </div>
    </el-dialog>

     <el-dialog :visible.sync="dialogFormVisibles">
      <el-form style="width: 80%" :model="Exam" >
        <el-form-item label="知识专题" label-width="100px">
          <el-input autocomplete="off" v-model="Exam.title"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisibles = false">添 加</el-button>
      </div>
    </el-dialog>

     <!-- 导入 -->
    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
            <el-upload
              :action="'http://42.194.159.131:8080/article/batchAddExam'"
               :headers="headers"
              :on-success="onUploadSuccess"
              :multiple="false"
              class="upload-demo"
              >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible=false">取消</el-button>
      </div>
    </el-dialog>
    <!-- --------------------------------------- -->
    <!-- --------------------------------------- -->
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import healexam from "@/api/healthyarticle";
export default {
  ////定义变量和初始值
  data() {
    //观看人数判断
      var checknum = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('内容不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          }else{
            callback();
          }
        }, 1000);
      };
    return {
      dialogFormVisibles: false, //对话框（查看）
      // -------------------------------------------日历
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      list: {
        image: "",
      }, //每页数据集合
      page_num: 1,
      page_size: 8, //每8个数据一页
      total: 1, //初始化
      searchObj: {}, //条件封装对象
       multipleSelection: [], //批量选择中选择的记录列表
      dialogImportVisible:false,//弹框
      dialogFormVisible: false, //对话框（查看）
      Exam: {
        image: "string",

        viewNum: 0,
      },
      headers: {
        Authorization: getToken(),
      },
      rules:{
         title: [
            { required: true, message: '请输入内容', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请输入类型', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
           startTime: [
            { type: 'date', required: true, message: '请选择开题日期、时间', trigger: 'blur' },
          ],
          endTime: [
            { type: 'date', required: true, message: '请选择截至日期、时间', trigger: 'blur' },
          ],
           viewNum:[
           { validator: checknum, trigger: 'blur' }
          ],
      }
    };
  },
  //在页面渲染前执行
  //调用methods定义的方法，得到数据

  created() {
    this.fetchData();
  },
  methods: {
    //时间格式化函数，此处仅针对yyyy-MM-dd hh:mm:ss 的格式进行格式化
    dateFormat: function (time) {
      var date = new Date(time);
      var year = date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      var hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      var minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      var seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },
    //导入数据字典
     importData(){
      this.dialogImportVisible = true
    },
     //上传成功调用
    onUploadSuccess(){
        this.dialogImportVisible = false
        this.fetchData(1);
        this.$message({
        	  message: '导入数据成功!',
        	  type: 'success'
          })
    },
    //导出数据字典
    exportData(){
      window.location.href="http://42.194.159.131:8080/article/exportExamData"
    },
      //获取选择复选框的id值
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
     //批量删除
    removeRows(){
         this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //遍历数组得到每个id值，设置到idList里面
          var idList = []
          for(var i =0;i< this.multipleSelection.length;i++){
            var obj =  this.multipleSelection[i];
            var id = obj.examId
            idList.push(id)
          }
          //调用接口
          healexam.batchRemoveExam(idList).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            console.log('aaaaaaaaaa',resp.message);
            //刷新页面数据
            this.fetchData(1);
          })
          .catch(()=>{
          
          this.$message({
            type: "error",
            message: "删除失败!权限不足，请联系管理员进行升级",
          });
        
       })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
     addType(){
    console.log('aaaaaaa');
    this.dialogFormVisibles = true;
  },
    addExam() {
      this.dialogFormVisible = true;
      //清除一下数组
      this.Exam = {
        image: "",
      };
    },
    //修改问题
    editExam(row) {
      console.log(row);
      this.dialogFormVisible = true;
      this.Exam = { ...row };
    },
    //页面列表页渲染，请求接口调用
    fetchData(page = 1) {
      this.page_num = page;
      var vm = this;
      healexam
        .getHealthyexamList(this.page_num, this.page_size, this.searchObj)
        //请求成功调用
        .then(function (res) {
          vm.list = res.data.Exam.list;
          vm.total = res.data.Exam.total;
        });
    },
    //页面列表页渲染，请求接口调用

    //添加或者修改确定按钮
     addorupdateExam() {
        //获取from结点，验证字段
      this.$refs.ruleForm.validate(async (success) => {
        //如果全部字段符合条件
        if (success) {
           this.dialogFormVisible = false;
      let result = await healexam.reqAddOrUpdateExam(this.Exam);
      console.log("aaaaaaaaaaaaaaaaaa", result);
      if (result.errorCode == 0) {
        this.$message({
          type: "success",
          message: this.Exam.examId ? "修改考试信息成功" : "添加考试信息成功",
        });
        this.fetchData(this.Exam.examId ? this.page_num : 1); // 更新商品列表
      }
        } else {
          return false;
        }
      });

    },
    delExam(examId) {
      console.log(examId);
      this.$confirm("此操作将永久删除该考试信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          healexam.delexam(examId).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面数据
            this.fetchData(1);
          })
          .catch(()=>{
          
          this.$message({
            type: "error",
            message: "删除失败!权限不足，请联系管理员进行升级",
          });
        
       })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //上传图片相关回调
    handleAvatarSuccess(res, file) {
      this.Exam.image = res.data.picUrl;
      console.log("上传图片成功", res);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      console.log("beforeAvatarUpload", file);
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // -------------------------------------------------
    // 查找考试ID信息------------------------------
    searchExam(examId) {
      console.log("aaaaaaaaaaa", examId);
      this.$router.push("/HealthyArticle/examinfo/" + examId);
    },
    // ---------------------------------------------------
  },
};
</script>

<style  scoped>
.line {
  text-align: center;
}

.box {
  margin-left: 200px;
  height: 1100px;
  width: 700px;
  border: solid rgb(187, 186, 187);
}
.avatar-uploader .el-upload {
  border: 3px dashed #decfcf;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
